<!--
  @author:  long
  @date:    2024/5/28
  @file:    xx
  @require:
-->
<template>
  <div class="backlog">
    <div class="backlog-header">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
        <el-tab-pane label="全部需求" name="first"></el-tab-pane>
        <el-tab-pane label="全部特性" name="feature"></el-tab-pane>
        <el-tab-pane label="全部用户故事" name="userStory"></el-tab-pane>
        <el-tab-pane label="进行中需求" name="fourth"></el-tab-pane>
        <!--        <el-tab-pane label="更多" name="more"></el-tab-pane>-->
      </el-tabs>
      <div class="createBtn">
        <el-popover placement="bottom-start" :width="200" trigger="click">
          <div
            @click="handleCreateWorkItem('epic')"
            class="flex items-center pl-5px py-8px cursor-pointer hover:bg-gray-100"
          >
            <img class="mr-5px" :src="epicSquareFill" alt="" />
            <span>史诗</span>
          </div>
          <div
            @click="handleCreateWorkItem('feature')"
            class="flex items-center pl-5px py-8px cursor-pointer hover:bg-gray-100"
          >
            <img class="mr-5px" :src="featureSquareFill" alt="" />
            <span>特性</span>
          </div>
          <div
            @click="handleCreateWorkItem('userStory')"
            class="flex items-center pl-5px py-8px cursor-pointer hover:bg-gray-100"
          >
            <img class="mr-5px" :src="userStorySquareFill" alt="" />
            <span>用户故事</span>
          </div>
          <template #reference>
            <el-button type="primary" icon="Plus">
              新建
              <el-icon class="el-icon--right">
                <CaretBottom />
              </el-icon>
            </el-button>
          </template>
        </el-popover>
      </div>
    </div>
    <div class="backlog-search">
      <el-row :gutter="10">
        <el-col :span="4">
          <el-input
            v-model="queryForm.title"
            style="width: 200px"
            placeholder="搜索"
            prefix-icon="Search"
            clearable
          />
        </el-col>
        <el-col :span="8">
          <el-button type="primary" icon="Search" @click="getList"
            >搜索
          </el-button>
          <el-button icon="RefreshRight" @click="queryList">重置</el-button>
          <el-button type="primary" icon="Filter" @click="openDrawer"
            >高级搜索
          </el-button>
          <el-button
            type="danger"
            icon="Delete"
            v-if="multipleSelection.length > 0"
            @click="handleEelBacklog"
            >删除
          </el-button>
        </el-col>

        <el-col :span="12" style="text-align: right">
          <el-tooltip
            class="item"
            effect="dark"
            :content="'自定义列表'"
            placement="top"
          >
            <el-button circle icon="Menu" @click="handleTable()" />
          </el-tooltip>
        </el-col>
      </el-row>
    </div>

    <!--   自定义列表   -->
    <el-table
      v-loading="loading"
      :data="tableList"
      row-key="id"
      border
      default-expand-all
      @selection-change="handleSelectionChange"
      @row-dblclick="handleTableRowDblclick"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      ></el-table-column>
      <el-table-column
        type="index"
        label="序号"
        width="60"
        align="center"
        fixed
      ></el-table-column>
      <el-table-column
        label="编号"
        align="left"
        prop="number"
        width="100"
        show-overflow-tooltip
        fixed
      ></el-table-column>
      <el-table-column label="标题" align="left" prop="title" width="300" fixed>
        <template #default="scope">
          <el-tooltip :content="scope.row.title" placement="top">
            <div class="flex items-center">
              <img
                class="mr-3"
                :src="backlogTypeIcon[scope.row.workItemType]"
              />
              <div>{{ scope.row.title }}</div>
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        v-for="(item, index) in tableCol.filter(item => item.show)"
        :key="index"
        v-bind="item"
      >
        <template #default="scope">
          <div v-if="item.prop == 'status'">
            <el-select
              v-model="scope.row[item.prop]"
              placeholder="状态"
              @change="
                val => {
                  handleTableSelectChange(val, scope.row, 'status')
                }
              "
            >
              <el-option
                v-for="(dict, index) in project_backlog_status"
                :label="dict.label"
                :value="dict.value"
                :key="index"
              ></el-option>
            </el-select>
          </div>
          <!--      优先级      -->
          <div v-if="item.prop == 'priority'">
            <el-select
              v-model="scope.row[item.prop]"
              placeholder="优先级"
              @change="
                val => {
                  handleTableSelectChange(val, scope.row, 'priority')
                }
              "
            >
              <el-option
                v-for="(dict, index) in project_backlog_priority"
                :label="dict.label"
                :value="dict.value"
                :key="index"
              ></el-option>
            </el-select>
          </div>
          <!--     风险      -->
          <div v-if="item.prop == 'risk'">
            <dict-tag
              :options="project_risk_level"
              :value="scope.row[item.prop]"
            />
          </div>
          <!--     需求来源      -->
          <div v-if="item.prop == 'source'">
            <el-select
              v-model="scope.row[item.prop]"
              placeholder="需求来源"
              @change="
                val => {
                  handleTableSelectChange(val, scope.row, 'source')
                }
              "
            >
              <el-option
                v-for="(dict, index) in project_backlog_source"
                :label="dict.label"
                :value="dict.value"
                :key="index"
              ></el-option>
            </el-select>
          </div>
          <!--     需求类型      -->
          <div v-if="item.prop == 'requirementType'">
            <el-select
              v-model="scope.row[item.prop]"
              placeholder="需求类型"
              @change="
                val => {
                  handleTableSelectChange(val, scope.row, 'requirementType')
                }
              "
            >
              <el-option
                v-for="(dict, index) in project_backlog_type"
                :label="dict.label"
                :value="dict.value"
                :key="index"
              ></el-option>
            </el-select>
          </div>
          <!--       进度      -->
          <div v-if="item.prop == 'percentage'">
            {{
              scope.row.workHour != null && scope.row.surplusWorkHour != ''
                ? (
                    (scope.row.workHour - scope.row.surplusWorkHour) /
                    scope.row.workHour
                  ).toFixed(2) *
                    100 +
                  '%'
                : '--'
            }}
          </div>
          <!--      描述      -->
          <div v-if="item.prop == 'description'">
            <div v-html="scope.row[item.prop]"></div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      class="h-45px"
      :total="tableTotal"
      v-model:page="queryForm.pageNum"
      v-model:limit="queryForm.pageSize"
      @pagination="getList"
    />

    <!-- 自定义订单列表弹窗 -->
    <DiaFixTable
      v-model="diaTable.open"
      :dialogParam="diaTable"
      @ok="diaTableFn"
    />

    <!-- 高级筛选 start -->
    <el-drawer class="p-0" size="700" v-model="drawer">
      <template #header>
        <div class="text-xl font-semibold">高级筛选</div>
      </template>
      <el-form
        label-position="right"
        :inline="true"
        :model="queryForm"
        class="demo-form-inline"
        label-width="80"
      >
        <el-row>
          <!--          <el-col :span="colSpan">-->
          <!--            <el-form-item label="编号">-->
          <!--              <el-input-->
          <!--                v-model="queryForm.id"-->
          <!--                placeholder="编号"-->
          <!--                style="width: 230px"-->
          <!--              ></el-input>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="colSpan">
            <el-form-item label="标题">
              <el-input
                v-model="queryForm.title"
                placeholder="标题"
                style="width: 230px"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="colSpan">
            <el-form-item label="状态">
              <el-select
                v-model="queryForm.status"
                placeholder="需求状态"
                style="width: 230px"
                clearable
              >
                <el-option
                  v-for="(dict, index) in project_backlog_status"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="colSpan">
            <el-form-item label="提出人">
              <el-input
                v-model="queryForm.createName"
                placeholder="提出人"
                style="width: 230px"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="colSpan">
            <el-form-item label="提出时间">
              <el-date-picker
                v-model="queryForm.createTime"
                type="date"
                placeholder="提出时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 230px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="colSpan">
            <el-form-item label="优先级">
              <el-select
                v-model="queryForm.priority"
                placeholder="需求优先级"
                style="width: 230px"
                clearable
              >
                <el-option
                  v-for="(dict, index) in project_backlog_priority"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="colSpan">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="queryForm.startDate"
                type="date"
                placeholder="开始时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 230px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="colSpan">
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="queryForm.endDate"
                type="date"
                placeholder="结束时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 230px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="colSpan">
            <el-form-item label="风险">
              <el-select
                v-model="queryForm.risk"
                placeholder="需求风险"
                style="width: 230px"
                clearable
              >
                <el-option
                  v-for="(dict, index) in project_risk_level"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="colSpan">
            <el-form-item label="需求来源">
              <el-select
                v-model="queryForm.source"
                placeholder="需求来源"
                style="width: 230px"
                clearable
              >
                <el-option
                  v-for="(dict, index) in project_backlog_source"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="colSpan">
            <el-form-item label="需求类型">
              <el-select
                v-model="queryForm.requirementType"
                placeholder="需求类型"
                style="width: 230px"
                clearable
              >
                <el-option
                  v-for="(dict, index) in project_backlog_type"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="drawer = false">关闭</el-button>
        <el-button type="primary" @click="handleDrawerSearch">确定</el-button>
      </template>
    </el-drawer>
    <!--   新建工作项   -->
    <create-work-item
      @queryList="queryList"
      ref="createWorkItemRef"
    ></create-work-item>
    <!--  工作项详情  -->
    <work-item-info
      ref="workItemInfoRef"
      @queryList="queryList"
    ></work-item-info>
  </div>
</template>

<script setup name="Backlog">
import epicSquareFill from '@/assets/icons/svg/epicSquareFill.svg'
import featureSquareFill from '@/assets/icons/svg/featureSquareFill.svg'
import userStorySquareFill from '@/assets/icons/svg/userStorySquareFill.svg'

import { getCurrentInstance, ref } from 'vue'
import useUserStore from '@/store/modules/user'
import {
  BACKLOGTABLE as INITTABLE //订单列表配置
} from '@/hooks/dict/backlog'
import CreateWorkItem from '@/views/researchManage/projectDetailsManage/modal/CreateWorkItem.vue'
import WorkItemInfo from '@/views/researchManage/projectDetailsManage/modal/WorkItemInfo.vue'
import {
  delBacklog,
  getBacklogList,
  updateBacklogProperty
} from '@/api/researchManage/backlog'
import { ElMessageBox } from 'element-plus'

const { proxy } = getCurrentInstance()
// 当前用户信息
const userStore = useUserStore()
//需求类型图标
const backlogTypeIcon = ref({
  epic: epicSquareFill,
  feature: featureSquareFill,
  userStory: userStorySquareFill
})
const activeName = ref('first')
// 搜索
const drawer = ref(false) //抽屉弹窗
const queryForm = ref({
  pageNum: 1,
  pageSize: 10,
  projectId: proxy.$route.query.projectId,
  id: '',
  title: '',
  status: '',
  ms: '',
  createTime: '',
  priority: '',
  startDate: '',
  endDate: '',
  risk: '',
  source: '',
  requirementType: ''
})
const colSpan = ref(12)
const loading = ref(false)
// 新建工作项ref
const createWorkItemRef = ref(null)
const workItemInfoRef = ref(null)
const tableTotal = ref(0)
const tableList = ref([])
const multipleSelection = ref([])

// 字典
const {
  project_backlog_status,
  project_backlog_priority,
  project_risk_level,
  project_backlog_source,
  project_backlog_type
} = proxy.useDict(
  'project_backlog_status',
  'project_backlog_priority',
  'project_risk_level',
  'project_backlog_source',
  'project_backlog_type'
)
//tab切换
const handleClick = val => {
  switch (val) {
    case 'first': //全部需求
      handleReset()
      queryForm.value.workItemType = ''
      getList()
      break
    case 'feature': //全部特性
      handleReset()
      queryForm.value.workItemType = 'feature'
      getList()
      break
    case 'userStory': //全部用户故事
      handleReset()
      queryForm.value.workItemType = 'userStory'
      getList()
      break
    case 'fourth': //进行中需求
      handleReset()
      queryForm.value.status = '2'
      getList()
      break
    case 'more':
      break
  }
}

//表格行双击
const handleTableRowDblclick = row => {
  workItemInfoRef.value.handleOpen(row)
}

// 删除操作
const handleEelBacklog = () => {
  let ids = multipleSelection.value
    .map(item => {
      return item.id
    })
    .join(',')
  ElMessageBox.confirm('是否删除选中的数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      delBacklog(ids).then(res => {
        getList()
      })
    })
    .catch(() => {})
}

//表格选择
const handleSelectionChange = val => {
  console.info(val)
  multipleSelection.value = val
}

//表格select修改
const handleTableSelectChange = (val, row, prop) => {
  console.info('row', row)
  let params = {
    id: row.id,
    key: prop,
    value: val
  }

  updateBacklogProperty(params).then(res => {
    getList()
  })
}

// 高级搜索
const handleDrawerSearch = () => {
  queryForm.value.pageNum = 1
  getList()
  drawer.value = false
}

// 重置
const handleReset = () => {
  queryForm.value = {
    pageNum: 1,
    pageSize: 10,
    projectId: proxy.$route.query.projectId,
    id: '',
    title: '',
    status: '',
    ms: '',
    createTime: '',
    priority: '',
    startDate: '',
    endDate: '',
    risk: '',
    source: '',
    requirementType: ''
  }
  switch (activeName.value) {
    case 'first':
      queryForm.value.workItemType = ''
      break
    case 'feature':
      queryForm.value.workItemType = 'feature'
      break
    case 'userStory':
      queryForm.value.workItemType = 'userStory'
      break
    case 'fourth':
      queryForm.value.status = '2'
      break
  }
  tableTotal.value = 0
}
// 重置搜索
const queryList = () => {
  handleReset()
  getList()
}

// 获取列表
const getList = () => {
  let params = JSON.parse(JSON.stringify(queryForm.value))
  getBacklogList(params).then(res => {
    tableTotal.value = res.data.total
    tableList.value = res.data.records
  })
  console.info('getlist')
}
//触发初始化
getList()

// 新建工作项
const handleCreateWorkItem = type => {
  createWorkItemRef.value.handleOpen(type)
}

/**
 * 打开高级筛选抽屉
 */
const openDrawer = () => {
  drawer.value = true
}

const tableCol = ref(INITTABLE)
// 自定义列表弹窗参数
const diaTable = ref({
  open: false,
  // tableName:'',
  tableCol: []
})

// 自定义列表
const handleTable = () => {
  diaTable.value = {
    open: true,
    tableName: 'backlogTable',
    tableCol: tableCol.value,
    initCol: INITTABLE
  }
}

// 获取列表配置
const diaTableFn = value => {
  tableCol.value = value
}

// 初始化表格
const initTable = () => {
  // 获取客户列表配置
  if (userStore.userInfo.listDisaplayObj?.backlogTable) {
    let _tableCol = JSON.parse(
      userStore.userInfo.listDisaplayObj['backlogTable']
    )
    // 过滤出本地新增的列
    let initItmes = INITTABLE.filter(
      item => !_tableCol.some(item1 => item1.prop == item.prop)
    )
    // 初始化列表配置
    tableCol.value = []
    _tableCol.forEach(item => {
      let newItem = {}
      for (const e of INITTABLE) {
        if (e.prop == item.prop) {
          newItem = { ...e, ...item, label: e.label }
          tableCol.value.push(newItem)
          break
        }
      }
    })
    tableCol.value = [...tableCol.value, ...initItmes]
  }
}
initTable()
</script>

<style scoped lang="scss">
.backlog {
  .backlog-header {
    border-bottom: 3px solid #eee;
    box-shadow: 0 4px 8px #00000008;
    position: relative;
    z-index: 2;
    height: 45px;
    line-height: 45px;
    display: flex;
    align-items: center;
    padding-left: 20px;

    :deep(.el-tabs__header) {
      margin-bottom: -2px;
    }

    .createBtn {
      position: absolute;
      right: 40px;
    }
  }

  .backlog-search {
    padding: 10px;
  }

  :deep(.el-table__placeholder) {
    display: none;
  }
}
</style>
